package cn.hpclub.server.controller.admin;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.ext.render.excel.PoiRender;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.model.ServiceReservation;
import cn.hpclub.server.service.BroadbandorderService;
import cn.hpclub.server.util.InterfaceUtil;

public class BroadbandreportController extends BaseAdminController<ServiceReservation>{
    private static Logger       log         = LoggerFactory.getLogger(BroadbandreportController.class);
    private static final String ORG_LIST    = "orgList";
    private static final String ORG_ID      = "org_id";
    private static final String CREATE_DATE = "create_date";
    private static final String START_DATE  = "start_date";
    private static final String END_DATE    = "end_date";

    /**
     * @Title: 获取列表
     */
    public void list(){
        String isExport = getPara("isExport");

        int defaultOrgId = iniOrgTree();
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        if(searchInfo.get(ORG_ID) == null){
            searchInfo.put(ORG_ID, String.valueOf(defaultOrgId));
        }
        if(searchInfo.get(CREATE_DATE) == null){
            try{
                setDateParam(searchInfo);
            }
            catch(ParseException e){
                e.printStackTrace();
            }
        }

        if("1".equals(isExport)){
            export(searchInfo);
        } else{
            query(searchInfo);
        }
    }

    private void export(ConcurrentHashMap<String, String> searchInfo){
        List<Record> listExport = BroadbandorderService.service.getListExport(searchInfo);

        PoiRender excel = PoiRender.me(listExport);
        String[] headesExport = BroadbandorderService.service.headesExport;
        String[] columnsExport = BroadbandorderService.service.columnsExport;

        render(excel.sheetName("预约信息报表").headers(headesExport).columns(columnsExport).fileName(generateFileName()));
    }

    String generateFileName(){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HHmmssSSS");
        String curTime = sdf.format(date);
        String fileName = "宽带预约-" + curTime + ".xlsx";
        // System.out.println("excel file name:" + fileName);
        try {
            return new String(fileName.getBytes("gbk"),"iso8859-1");
        } catch (UnsupportedEncodingException e) {
            log.info(e.getMessage());
        }
        return fileName;
    }

    private void query(ConcurrentHashMap<String, String> searchInfo){
        findByPageBroadbandReservation(searchInfo);
        setAttrs(searchInfo);
        render("/admin/broadband_report_list.tpl");
    }

    private void setDateParam(ConcurrentHashMap<String, String> searchInfo) throws ParseException{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String endDate = sdf.format(new java.util.Date());
        Calendar c = Calendar.getInstance();
        c.setTime(sdf.parse(endDate));
        c.add(Calendar.MONTH, -1); // 得到前一个月
        String startDate = sdf.format(c.getTime());
        String createDate = startDate + "|" + endDate;

        log.info("createDate =" + createDate);
        searchInfo.put(START_DATE, startDate);
        searchInfo.put(END_DATE, endDate);
        searchInfo.put(CREATE_DATE, createDate);
    }

    @SuppressWarnings("static-access")
    private void findByPageBroadbandReservation(ConcurrentHashMap<String, String> searchInfo){
        String select = BroadbandorderService.service.getListSqlSelect();
        String sqlExceptSelect = BroadbandorderService.service.getSqlExceptSelect(searchInfo);
        int pageNumber = getParaToInt("pageNumber", 1);
        Page<ServiceReservation> pager = ServiceReservation.dao.paginate(pageNumber, getParaToInt("pageSize", 10),
                                                                         select, sqlExceptSelect);
        /* 删除最后一页所有数据后，显示最后一页前一页 */
        if(pager.getPageNumber() > 1 && pager.getList().size() == 0){
            pager = ServiceReservation.dao.paginate(pageNumber - 1, getParaToInt("pageSize", 10), select,
                                                    sqlExceptSelect);
        }

        setAttr("pager", pager);
    }

    private int iniOrgTree(){
        List<Entry<String, String>> orgList = InterfaceUtil.getOrgList();
        setAttr(ORG_LIST, orgList);
        if(orgList.size() > 0){
            return Integer.parseInt(orgList.get(0).getValue());
        } else{
            return 0;
        }
    }
}
